import win32gui
import win32api
import win32process
import ctypes
import win32security
import win32con
import ctypes.wintypes
import time
from ctypes import *
from Tool import factors


W = 0x57  # Up
A = 0x41  # Left
S = 0x53  # Down
D = 0x44  # Right

J = 0x4A  # LK
K = 0x4B  # MK
U = 0x55  # LP
I = 0x49  # MP


MapVirtualKey = ctypes.windll.user32.MapVirtualKeyA  # Virtual Hardware Mapping
def byte2Float(s):  # Convert byte to float
    try:
        i = int(s, 10)  # convert from Dec to a Python int
        cp = pointer(c_int(i))  # make this into a c integer
        fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
        a = fp.contents.value
    except:
        a = 0
    finally:
        return a

def restart(hp):
    rivalHP = hp.get_value(rivalhpaddr)
    selfHP = hp.get_value(selfhpaddr)
    while rivalHP+selfHP <= 500:
        win32api.keybd_event(J, MapVirtualKey(J, 0), 0, 0)
        time.sleep(0.2)
        win32api.keybd_event(J, MapVirtualKey(J, 0), win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(0.1)
        rivalHP = hp.get_value(rivalhpaddr)
        selfHP = hp.get_value(selfhpaddr)
        if rivalHP+selfHP == 1000:
            break

if __name__ == "__main__":
    #get_extra_privs()
    hp = factors.Hp_getter()
    seloc = hp.get_self_addr()
    rivloc = hp.get_rival_addr()
    selfhpaddr = hp.get_self_HP_addr()
    rivalhpaddr = hp.get_rival_HP_addr()
    while True:
        playerx = int(byte2Float(str(hp.get_value(seloc))))
        rivalx = int(byte2Float(str(hp.get_value(rivloc))))
        selfHP = hp.get_value(selfhpaddr)
        rivalHP = hp.get_value(rivalhpaddr)
        print(rivalHP,selfHP)
        if rivalHP == 0 or selfHP == 0:
            print('eposide ends')
            restart(hp)
